//
//  CycleTool+HttpTool.m
//  CDSBZX
//
//  Created by dihuijun on 17/3/2.
//  Copyright © 2017年 Cycle. All rights reserved.
//  

#import "CycleTool+HttpTool.h"

@implementation CycleTool (HttpTool)



/**
 *  含有头部请求
 *  @param method        请求方式 GET/POST
 *  @param timeInterval  设置超时时间
 *  @param url           url
 *  @param success       请求成功的回调
 *  @param failure       请求失败的回调
 */
+ (void)CycleHttpMethod:(NSString *)method setTimeOutInterval:(CGFloat)timeInterval withUrl:(NSString *)url success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    
    //1.以免有中文进行UTF编码
    NSString *UTFPathUrl               = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    //2.请求路径
    NSURL *urlPath                     = [NSURL URLWithString:UTFPathUrl];
    //3.创建请求对象
    NSMutableURLRequest *request       = [NSMutableURLRequest requestWithURL:urlPath];
    //4.设置请求方法
    request.HTTPMethod                 = method;
    //5.设置请求超时
    request.timeoutInterval            = timeInterval;
    //6.创建session配置对象
    NSURLSessionConfiguration  *config = [NSURLSessionConfiguration defaultSessionConfiguration];
    //7.创建session对象
    NSURLSession *session              = [NSURLSession sessionWithConfiguration:config];
    //8.添加网络任务
    NSURLSessionTask *task             = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            failure(error);
        }else{
            //将data转化成 NSString,在转化成字典
            NSString *dataString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
            dataString = [dataString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            
            ///判断首字母是否是字典或者数组或者String类型
            NSString *strFirstNumber = [[dataString substringFromIndex:0]substringToIndex:1];
            
            
            
            if (dataString==nil) {
                success(nil);
            }else{
                
                if ([strFirstNumber isEqualToString:@"{"]) {
                    NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
                    
                    NSError *error;
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                    if (error) {
                        NSLog(@"json解析失败:%@",error);
                    }else{
                        success(dict);
                    }
                }else if([strFirstNumber isEqualToString:@"["]){
                    
                    NSData *jsonData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
                    
                    NSError *error;
                    NSArray *Arraydict = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
                    if (error) {
                        NSLog(@"json解析失败:%@",error);
                    }else{
                        success(Arraydict);
                    }
                }else if([strFirstNumber isKindOfClass:[NSString class]]){
                    success(dataString);
                }else{
                    NSLog(@"%@",dataString);
                }
                
                
            }
            
        }
    }];
    //9.执行任务
    [task resume];
    
}

@end
